<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import type { CrudTableModel } from '~@/api/list/crud-table'
import { addUser, updateUser } from '~@/api/list/crud-table'
import { message as Message } from 'ant-design-vue';

const emit = defineEmits(['cancel', 'ok'])

const isUpdate = ref(false)

const visible = ref(false)

const title = computed(() => {
  return isUpdate.value ? '编辑' : '新增'
})

const formRef = ref<FormInstance>()

const formData = ref<CrudTableModel>({
  userName: '',
  userPassword: '',
  userAccount:'',
  roleIds:[]
})

const labelCol = { style: { width: '100px' } }
const wrapperCol = { span: 24 }

function open(record?: CrudTableModel) {
  visible.value = true
  isUpdate.value = !!record?.id
  formData.value = cloneDeep(record) ?? {
    userName: '',
    userPassword: '',
    userAccount:'',
    roleIds:[]
  }
}

async function handleOk() {
  try {
    await formRef.value?.validate()
    if(title.value === '新增') {
      const { message } =  await addUser({
        ...formData.value
      })
      // console.log(message)
      Message.success(message)      
    }
    if(title.value === '编辑') {
      const { message } = await updateUser({
        ...formData.value
      })
      Message.success(message) 
    }
    // 新增用户接口

    emit('ok')
    visible.value = false
  }
  catch (errorInfo) {
    console.log('Form Validate Failed:', errorInfo)
  }
}

function handleCancel() {
  formRef.value?.resetFields()
  emit('cancel')
}

/* const handleChange = (value: any) => {
  console.log(`selected ${value}`);
}; */

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" :title="title" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" class="w-full" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item name="userName" label="用户昵称" :rules="[{ required: true, message: '请输入用户昵称' }]">
        <a-input v-model:value="formData.userName" :maxlength="50" placeholder="请输入用户昵称" />
      </a-form-item>
      <a-form-item name="userAccount" label="用户账号" :rules="[{ required: true, message: '请输入用户账号' }]">
        <a-input v-model:value="formData.userAccount" :maxlength="50" placeholder="请输入用户账号" />
      </a-form-item>
      <a-form-item name="userPassword" label="用户密码" :rules="[{ required: true, message: '请输入用户密码' }]">
        <a-input v-model:value="formData.userPassword" :maxlength="50" placeholder="请输入用户密码" />
      </a-form-item>
      <a-form-item name="roleIds" label="用户角色" :rules="[{ required: true, message: '请选择用户角色' }]">
        <a-select
          v-model:value="formData.roleIds"
          mode="multiple"
          style="width: 100%"
          placeholder="请选择用户角色"
          :options="[...Array(25)].map((_, i) => ({ value: (i + 10) + (i + 1) }))"
        ></a-select>
      </a-form-item>
    </a-form>
  </a-modal>

</template>
